package com.arron.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Classname ReadWriteLockDemo
 * @Description TODO
 * @Date 2020/8/21 2:22
 * @Created by 刘
 */

class MyCache{

    private volatile Map<String,Object> map =  new HashMap<>();
//    new ConcurrentHashMap
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key,Object value){

        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t正在写");
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t写完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    public Object get(String key){
        readWriteLock.readLock().lock();
        Object o = null;
        try {
            System.out.println(Thread.currentThread().getName()+"\t正在读");
            o = map.get(key);
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"\t读完成"+o);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }


        return o;
    }

}




/**
 *  使用读写锁实现一个本地缓存，实现读写分离思想
 *  缓存3大基本方法：写，读，清空
 *  读读--共存
 *  读写--不共存
 *  写写--不共存
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();

        /**
         *  10个线程写
         */
        for (int i = 1; i <= 10; i++) {
             final int finalI = i;
             new Thread(()->{
                 myCache.put(finalI +"", finalI +"");
             },String.valueOf(i)).start();
         }

        /**
         *  10个线程读
         */
        for (int i = 1; i <= 10; i++) {
            final int finalI = i;
            new Thread(()->{
                myCache.get(String.valueOf(finalI));
            },String.valueOf(i)).start();
        }


    }




}
